<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="1600px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="relative flex flex-row border border-gray-300" style="height: 680px">
      <div v-loading="tableLoading" class="w-1/4 py-2 px-4 flex flex-col">
        <div class="text-xl py-2 font-bold">表单属性</div>
        <el-scrollbar class="flex-1 overflow-auto">
          <el-form ref="tableRef" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="表名" prop="tableName">
              <div class="flex flex-row w-full">
                <el-input
                  v-model.trim="form.tableName"
                  placeholder="请输入表名"
                  :disabled="!!form.id"
                >
                  <template v-if="!!form.id" #append>
                    <el-icon class="cursor-pointer" @click="handleCopyClick(form.tableName)">
                      <DocumentCopy />
                    </el-icon>
                  </template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item label="表单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入表单名称" />
            </el-form-item>
            <el-form-item label="表单描述" prop="tableRemark">
              <el-input v-model="form.tableRemark" placeholder="请输入表单描述" />
            </el-form-item>

            <el-form-item label="目标数据源" prop="dataSourceId">
              <el-select
                v-model="form.dataSourceId"
                placeholder="请选择目标数据源"
                clearable
                filterable
                :disabled="!!form.id"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dataSourceIdOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="表单编码" prop="tableCode">
              <el-input v-model="form.tableCode" placeholder="请输入表单编码" />
            </el-form-item>
            <el-form-item label="主键策略" prop="idStrategy">
              <el-select
                v-model="form.idStrategy"
                placeholder="请选择主键策略"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in idStrategyOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.idStrategy === '序列'" label="序列名称" prop="seqName">
              <el-input
                v-model="form.seqName"
                placeholder="请输入序列名称"
                @input="(v) => handleFormItemUpperCase(v, 'seqName')"
              />
            </el-form-item>
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签，多个用、分隔" />
            </el-form-item>
            <el-form-item label="数据权限方式" prop="dataScopeType">
              <el-select
                v-model="form.dataScopeType"
                placeholder="请选择数据权限方式"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="(key, val) in dataScopeTypeOptions"
                  :key="key"
                  :label="val"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="form.dataScopeType !== 'noLimit' && form.dataScopeType"
              label="用户ID字段名"
              prop="userIdFieldName"
            >
              <el-select
                v-model="form.userIdFieldName"
                clearable
                filterable
                placeholder="请选择用户ID字段名"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, idx) in getAllField()"
                  :key="idx"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="form.dataScopeType === 'byDept'"
              label="部门ID字段名"
              prop="deptIdFieldName"
            >
              <el-select
                v-model="form.deptIdFieldName"
                clearable
                filterable
                placeholder="请选择部门ID字段名"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, idx) in getAllField()"
                  :key="idx"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <div v-if="form.dataScopeType === 'byXzqh'">
              <el-form-item label="区字段名" prop="quFieldName">
                <el-select
                  v-model="form.quFieldName"
                  clearable
                  filterable
                  placeholder="请选择区字段名"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, idx) in getAllField()"
                    :key="idx"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="街道字段名" prop="jdFieldName">
                <el-select
                  v-model="form.jdFieldName"
                  clearable
                  filterable
                  placeholder="请选择街道字段名"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, idx) in getAllField()"
                    :key="idx"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="社区字段名" prop="sqFieldName">
                <el-select
                  v-model="form.sqFieldName"
                  clearable
                  filterable
                  placeholder="请选择社区字段名"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, idx) in getAllField()"
                    :key="idx"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="网格字段名" prop="wgFieldName">
                <el-select
                  v-model="form.wgFieldName"
                  clearable
                  filterable
                  placeholder="请选择网格字段名"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, idx) in getAllField()"
                    :key="idx"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="小区字段名" prop="xqFieldName">
                <el-select
                  v-model="form.xqFieldName"
                  clearable
                  filterable
                  placeholder="请选择小区字段名"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, idx) in getAllField()"
                    :key="idx"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </el-scrollbar>
      </div>

      <div class="absolute left-1/4 bg-gray-200 w-1 h-full"></div>

      <div class="w-3/4 pl-5 pr-4 pb-2 flex flex-col">
        <div v-show="!isAddCol && !isEditCol">
          <div class="text-xl pt-4 pb-2 pl-4 font-bold">表单列清单</div>

          <div class="flex flex-row justify-start items-center">
            <el-button type="primary" icon="Plus" @click="handleAddColItem">新增</el-button>
            <el-button
              type="danger"
              icon="Delete"
              :disabled="multipleCols"
              @click="handleBatchDelColItem"
            >
              批量删除
            </el-button>
          </div>

          <el-tabs v-model="activeFieldProperty">
            <el-tab-pane label="基本属性" name="基本属性" />
            <el-tab-pane label="数据库属性" name="数据库属性" />
            <el-tab-pane label="页面属性" name="页面属性" />
            <el-tab-pane label="字典属性" name="字典属性" />
            <el-tab-pane label="校验配置" name="校验配置" />
          </el-tabs>

          <el-table
            v-loading="tableLoading"
            border
            stripe
            height="530"
            :data="form.formCols"
            @selection-change="handleColSelectionChange"
          >
            <el-table-column align="center" type="selection" width="50" fixed="left" />
            <el-table-column align="center" label="列名（中文）" prop="fieldName" fixed="left" />
            <el-table-column align="center" label="列名（英文）" prop="colName" fixed="left" />

            <template v-if="activeFieldProperty === '基本属性'">
              <el-table-column
                align="center"
                label="字段描述"
                prop="fieldRemark"
                show-overflow-tooltip
              />
              <el-table-column align="center" label="排序" prop="sortValue" width="70" />
            </template>

            <template v-if="activeFieldProperty === '数据库属性'">
              <el-table-column
                align="center"
                label="字段类型"
                prop="fieldType"
                :formatter="formatFieldType"
              />
              <el-table-column align="center" label="长度" prop="fieldLength" />
              <el-table-column
                align="center"
                label="小数"
                prop="fieldDecimalLength"
                :formatter="formatFieldDecimalLength"
              />
              <el-table-column align="center" label="默认值" prop="fieldDefault" />
              <el-table-column
                align="center"
                label="是否主键"
                prop="primary"
                :formatter="formatBool"
              />
              <el-table-column
                align="center"
                label="是否自增"
                prop="autoIncrement"
                :formatter="formatBool"
              />
              <el-table-column
                align="center"
                label="允许空值"
                prop="allowNull"
                :formatter="formatBool"
              />
            </template>

            <template v-if="activeFieldProperty === '页面属性'">
              <el-table-column align="center" label="列表状态" prop="listStatus" />
              <el-table-column align="center" label="新增状态" prop="insertStatus" />
              <el-table-column align="center" label="修改状态" prop="updateStatus" />
              <el-table-column
                align="center"
                label="后端填充表达式"
                prop="autoFillExp"
                :formatter="formatAutoFillExp"
              />
              <el-table-column
                align="center"
                label="前端填充表达式"
                prop="autoFillExpWeb"
                :formatter="formatAutoFillExpWeb"
              />
              <el-table-column
                align="center"
                label="仅新增时填充"
                prop="onlyInsert"
                :formatter="formatBool"
              />
              <el-table-column
                align="center"
                label="控件类型"
                prop="controlType"
                :formatter="formatControlType"
              />
              <el-table-column align="center" label="日期/时间格式" prop="format" />
              <el-table-column
                align="center"
                label="查询条件"
                prop="queryCondition"
                :formatter="formatQueryCondition"
              />
              <el-table-column label="是否需要脱敏" align="center" prop="needDesensitize">
                <template #default="scope">
                  <span>{{ formatBoolean(scope.row.needDesensitize) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="脱敏方式"
                align="center"
                prop="desensitizationType"
                :formatter="formatDesensitization"
              />
            </template>

            <template v-if="activeFieldProperty === '字典属性'">
              <el-table-column align="center" label="字典类型" prop="relationDictType" />
              <el-table-column align="center" label="系统字典类型" prop="sysDictType" />
              <el-table-column align="center" label="常量字典内容" prop="constantDictContent" />
            </template>

            <template v-if="activeFieldProperty === '校验配置'">
              <el-table-column
                align="center"
                label="是否必填"
                prop="required"
                :formatter="formatBool"
              />
              <el-table-column
                align="center"
                label="是否唯一"
                prop="unique"
                :formatter="formatBool"
              />
              <el-table-column align="center" label="校验器" prop="validator" />
              <el-table-column align="center" label="正则校验" prop="regexpStr" />
            </template>

            <el-table-column label="操作" align="center" fixed="right" width="140">
              <template #default="{ row }">
                <div class="flex flex-row justify-center items-center">
                  <el-button link icon="Edit" @click="handleEditColItem(row)"> 修改 </el-button>
                  <el-button
                    link
                    style="color: red"
                    icon="Delete"
                    :disabled="row.colName === 'ID'"
                    @click="handleDelColItem(row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-show="isAddCol || isEditCol" class="flex flex-col h-full">
          <div class="text-xl my-4 font-bold">
            表单列{{ isAddCol ? '新增' : '' }}{{ isEditCol ? '修改' : '' }}
          </div>
          <el-scrollbar class="flex-1 overflow-auto">
            <el-form
              ref="colItemFormRef"
              :model="currItem"
              :rules="colItemRules"
              label-width="140px"
            >
              <el-divider content-position="left">
                <span class="font-bold text-base">基本属性</span>
              </el-divider>
              <div class="flex flex-row flex-wrap">
                <el-form-item label="列名（中文）" prop="fieldName" class="w-1/2">
                  <el-input v-model.trim="currItem.fieldName" @change="handleFieldNameChange" />
                  <!--                    @input="(v) => handleColItemChinese(v, 'fieldName')"-->
                </el-form-item>
                <el-form-item label="列名（英文）" prop="colName" class="w-1/2">
                  <el-input v-model="currItem.colName" maxlength="29" />
                </el-form-item>
                <el-form-item label="排序" prop="sortValue" class="w-1/2">
                  <el-input-number v-model="currItem.sortValue" :min="1" class="!w-full" />
                </el-form-item>
                <el-form-item label="字段描述" prop="fieldRemark" class="w-1/2">
                  <el-input v-model="currItem.fieldRemark" />
                </el-form-item>
              </div>

              <el-divider content-position="left">
                <span class="font-bold text-base">数据库属性</span>
              </el-divider>
              <div class="flex flex-row flex-wrap relative">
                <el-form-item label="字段类型" prop="fieldType" class="w-1/2">
                  <el-select
                    v-model="currItem.fieldType"
                    clearable
                    filterable
                    :disabled="currItem.fieldTypeDisable"
                    class="!w-full"
                    @change="handleFieldTypeChange(currItem)"
                  >
                    <el-option
                      v-for="item in fieldOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="长度" prop="fieldLength" class="w-1/2">
                  <el-input-number v-model="currItem.fieldLength" :min="1" class="!w-full" />
                </el-form-item>
                <el-form-item label="小数" prop="fieldDecimalLength" class="w-1/2">
                  <el-input-number
                    v-model="currItem.fieldDecimalLength"
                    class="!w-full"
                    :min="0"
                    :disabled="checkFieldDecimalLengthDisabled(currItem)"
                  />
                </el-form-item>
                <el-form-item label="默认值" prop="fieldDefault" class="w-1/2">
                  <el-input
                    v-model.trim="currItem.fieldDefault"
                    @input="handleFieldDefaultChange"
                  />
                </el-form-item>
                <el-form-item label="是否主键" prop="primary" class="w-1/2">
                  <el-switch
                    v-model="currItem.primary"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    :active-value="true"
                    :inactive-value="false"
                    @change="handleIsPrimaryChange(currItem)"
                  />
                </el-form-item>
                <el-form-item label="是否自增" prop="autoIncrement" class="w-1/2">
                  <el-switch
                    v-model="currItem.autoIncrement"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    :active-value="true"
                    :inactive-value="false"
                    :disabled="autoIncrementDisabled(currItem)"
                  />
                </el-form-item>
                <el-form-item label="允许空值" prop="allowNull" class="w-1/2">
                  <el-switch
                    v-model="currItem.allowNull"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    :active-value="true"
                    :inactive-value="false"
                    :disabled="currItem.primary"
                  />
                </el-form-item>
              </div>

              <el-divider content-position="left">
                <span class="font-bold text-base">页面属性</span>
              </el-divider>
              <div class="flex flex-row flex-wrap">
                <el-form-item label="列表状态" prop="listStatus" class="w-1/2">
                  <el-select v-model="currItem.listStatus" clearable filterable class="!w-full">
                    <el-option
                      v-for="item in listStatusOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="查询条件" prop="queryCondition" class="w-1/2">
                  <el-select
                    v-model="currItem.queryCondition"
                    clearable
                    filterable
                    class="!w-full"
                    :disabled="checkQueryConditionDisabled(currItem)"
                  >
                    <el-option
                      v-for="item in queryOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                      :disabled="checkQueryConditionItemDisabled(currItem, item.value)"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="新增状态" prop="insertStatus" class="w-1/2">
                  <el-select v-model="currItem.insertStatus" clearable filterable class="!w-full">
                    <el-option
                      v-for="item in statusOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="修改状态" prop="updateStatus" class="w-1/2">
                  <el-select v-model="currItem.updateStatus" clearable filterable class="!w-full">
                    <el-option
                      v-for="item in statusOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="!currItem.autoFillExpWeb"
                  label="后端填充表达式"
                  prop="autoFillExp"
                  class="w-1/2"
                >
                  <el-select
                    v-model="currItem.autoFillExp"
                    clearable
                    filterable
                    allow-create
                    class="!w-full"
                    placeholder="请选择或手动输入"
                  >
                    <el-option
                      v-for="item in autoFillExpOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="!currItem.autoFillExp"
                  label="前端填充表达式"
                  prop="autoFillExpWeb"
                  class="w-1/2"
                >
                  <el-select
                    v-model="currItem.autoFillExpWeb"
                    placeholder="前端填充表达式"
                    clearable
                    filterable
                    allow-create
                    class="!w-full"
                  >
                    <el-option
                      v-for="(value, key) in autoFillExpList"
                      :key="key"
                      :label="key"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="currItem.autoFillExp || currItem.autoFillExpWeb"
                  label="仅新增时填充"
                  prop="onlyInsert"
                  class="w-1/2"
                >
                  <el-radio-group v-model="currItem.onlyInsert" placeholder="请选择">
                    <el-radio :value="true" size="large" label="是" />
                    <el-radio :value="false" size="large" label="否" />
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="控件类型" prop="controlType" class="w-1/2">
                  <el-select
                    v-model="currItem.controlType"
                    clearable
                    filterable
                    class="!w-full"
                    @change="handleControlTypeChange(currItem)"
                  >
                    <el-option
                      v-for="item in controlOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="
                    ['DatePicker', 'TimePicker', 'DatetimePicker'].includes(currItem.controlType)
                  "
                  :label="`${currItem.controlType?.includes('Date') ? '日期' : ''}${currItem.controlType?.toLowerCase()?.includes('time') ? '时间' : ''}格式`"
                  prop="format"
                  class="w-1/2"
                >
                  <el-select v-model="currItem.format" clearable filterable class="!w-full">
                    <el-option
                      v-for="item in formatOptions.filter((k) => k.type === currItem.controlType) ??
                      []"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否需要脱敏" prop="needDesensitize" class="w-1/2">
                  <el-radio-group
                    v-model="currItem.needDesensitize"
                    placeholder="请选择是否需要脱敏"
                    @change="handleNeedDesensitizeChange(currItem)"
                  >
                    <el-radio :value="true" size="large" label="是" />
                    <el-radio :value="false" size="large" label="否" />
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="currItem.needDesensitize"
                  label="脱敏方式"
                  prop="desensitization"
                  class="w-1/2"
                >
                  <el-select
                    v-model="currItem.desensitizationType"
                    clearable
                    placeholder="请选择脱敏方式"
                  >
                    <el-option
                      v-for="(item, key) in supportedDesensitizationObj"
                      :key="key"
                      :value="key"
                      :label="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="使用此字段排序" prop="useOrderBy" class="w-1/2">
                  <el-select
                    v-model="currItem.useOrderBy"
                    clearable
                    filterable
                    class="!w-full"
                    placeholder="请选择排序方式"
                  >
                    <el-option label="升序" value="aesc" />
                    <el-option label="降序" value="desc" />
                    <el-option label="不使用" value="不使用" />
                  </el-select>
                </el-form-item>
              </div>

              <template
                v-if="
                  ['radio', 'checkbox', 'select', 'AddressPicker'].includes(currItem.controlType)
                "
              >
                <el-divider content-position="left">
                  <span class="font-bold text-base">字典属性</span>
                </el-divider>
                <div class="flex flex-row flex-wrap">
                  <el-form-item label="字典类型" prop="relationDictType" class="w-1/2">
                    <el-select
                      v-model="currItem.relationDictType"
                      clearable
                      filterable
                      class="!w-full"
                      @change="handleRelationDictTypeChange(currItem)"
                    >
                      <el-option value="系统字典" label="系统字典" />
                      <el-option value="常量字典" label="常量字典" />
                      <el-option value="行政区划" label="行政区划" />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    v-if="currItem.relationDictType === '系统字典'"
                    label="系统字典类型"
                    prop="sysDictType"
                    class="w-1/2"
                  >
                    <el-input v-model="currItem.sysDictType" />
                  </el-form-item>
                  <el-form-item
                    v-if="currItem.relationDictType === '常量字典'"
                    label="常量字典内容"
                    prop="constantDictContent"
                    class="w-1/2"
                  >
                    <el-input v-model="currItem.constantDictContent" placeholder="k1=v1,k2=v2" />
                  </el-form-item>
                  <template v-if="currItem.relationDictType === '行政区划'">
                    <el-form-item label="行政区划类型" prop="xzqhlx" class="w-1/2">
                      <el-select v-model="currItem.xzqhlx" clearable filterable class="!w-full">
                        <el-option
                          v-for="item in xzqhOptions"
                          :key="item.value"
                          :value="item.value"
                          :label="item.label"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="上级行政区划" prop="parentXzqhField" class="w-1/2">
                      <el-select
                        v-model="currItem.parentXzqhField"
                        clearable
                        filterable
                        class="!w-full"
                      >
                        <el-option
                          v-for="item in getAllField()"
                          :key="item.value"
                          :value="item.value"
                          :label="item.label"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </div>
              </template>

              <el-divider content-position="left">
                <span class="font-bold text-base">校验配置</span>
              </el-divider>
              <div class="flex flex-row flex-wrap">
                <el-form-item label="是否必填" prop="required" class="w-1/2">
                  <el-switch
                    v-model="currItem.required"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    :active-value="true"
                    :inactive-value="false"
                  />
                </el-form-item>
                <el-form-item label="是否唯一" prop="unique" class="w-1/2">
                  <el-switch
                    v-model="currItem.unique"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    :active-value="true"
                    :inactive-value="false"
                  />
                </el-form-item>
                <el-form-item label="校验器" prop="validator" class="w-1/2">
                  <el-select v-model="currItem.validator" clearable filterable class="!w-full">
                    <el-option
                      v-for="item in validatorOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="正则校验" prop="regexpStr" class="w-1/2">
                  <el-input v-model="currItem.regexpStr" />
                </el-form-item>
              </div>
            </el-form>
          </el-scrollbar>
          <div class="flex justify-around items-center mt-2">
            <el-button type="primary" style="width: 200px" @click="handleConfirmItem">
              保存表单列
            </el-button>
            <el-button style="width: 200px" @click="handleCancelItem">取消</el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, unref, computed, watch, defineEmits, defineProps } from 'vue';
  import { getTable, addTable, updateTable, allowToModify } from '@/api/web/bu/form';
  import { useCopyToClipboard } from '@/hooks/web/useCopyToClipboard';
  import { useAutoFillExpOptions, useFieldOptions, useOptions } from './useConstant';
  import { randomString } from '@/utils';
  import pinyin from 'pinyin';
  import modal from '@/plugins/modal';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    dataSourceIdOptions: {
      type: Array,
      default: () => [],
    },
    detailId: {
      type: String,
      default: '',
    },
  });
  const emits = defineEmits(['update:modelValue', 'success']);

  const visible = computed({
    set(v) {
      emits('update:modelValue', v);
    },
    get() {
      return props.modelValue;
    },
  });

  const { clipboardRef, copiedRef } = useCopyToClipboard();
  const { autoFillExpOptions, formatAutoFillExp } = useAutoFillExpOptions();
  const { fieldOptions, formatFieldType } = useFieldOptions();
  const {
    formatOptions,
    xzqhOptions,
    listStatusOptions,
    statusOptions,
    controlOptions,
    formatControlType,
    validatorOptions,
    autoFillExpList,
    formatAutoFillExpWeb,
    queryOptions,
    formatQueryCondition,
    idStrategyOptions,
    dataScopeTypeOptions,
    supportedDesensitizationObj,
    formatDesensitization,
  } = useOptions();

  const title = ref('');
  const submitLoading = ref(false);
  const tableLoading = ref(false);
  const tableRef = ref(null);
  const colItemFormRef = ref(null);

  const isAddCol = ref(false);
  const isEditCol = ref(false);
  const currItem = ref({});
  const originalItem = ref({});
  const activeFieldProperty = ref('基本属性');
  const selectedCols = ref([]);
  const multipleCols = computed(() => !selectedCols.value.length);

  const form = ref({});
  const rules = ref({
    name: [{ required: true, message: '表单名称不能为空', trigger: 'blur' }],
    tableName: [
      { required: true, message: '表名不能为空', trigger: 'blur' },
      { pattern: /^[a-zA-Z][0-9a-zA-Z_]{0,29}$/, message: '请输入正确的表名', trigger: 'blur' },
    ],
    tableCode: [{ required: true, message: '表单编码不能为空', trigger: 'blur' }],
    idStrategy: [{ required: true, message: '主键策略不能为空', trigger: 'blur' }],
    seqName: [{ required: true, message: '序列名称不能为空', trigger: 'blur' }],
    tableRemark: [{ required: true, message: '表单描述不能为空', trigger: 'blur' }],
    dataScopeType: [{ required: true, message: '数据权限方式不能为空', trigger: 'blur' }],
    userIdFieldName: [{ required: true, message: '用户ID字段名不能为空', trigger: 'blur' }],
    deptIdFieldName: [{ required: true, message: '部门ID字段名不能为空', trigger: 'blur' }],
    // quFieldName: [{ required: true, message: '区字段名不能为空', trigger: 'blur' }],
    jdFieldName: [{ required: true, message: '街道字段名不能为空', trigger: 'blur' }],
    sqFieldName: [{ required: true, message: '社区字段名不能为空', trigger: 'blur' }],
    // wgFieldName: [{ required: true, message: '网格字段名不能为空', trigger: 'blur' }],
    // xqFieldName: [{ required: true, message: '小区字段名不能为空', trigger: 'blur' }],
    dataSourceId: [{ required: true, message: '目标数据源不能为空', trigger: 'blur' }],
  });
  const colItemRules = ref({
    colName: [
      { required: true, message: '列名（英文）不能为空', trigger: 'blur' },
      { pattern: /^[a-zA-Z][0-9a-zA-Z_]{0,29}$/, message: '请输入正确的表名', trigger: 'blur' },
    ],
    fieldName: [{ required: true, message: '列名（中文）不能为空', trigger: 'blur' }],
    sortValue: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
    fieldType: [{ required: true, message: '字段类型不能为空', trigger: 'blur' }],
    fieldLength: [{ required: true, message: '长度不能为空', trigger: 'blur' }],
    listStatus: [{ required: true, message: '列表状态不能为空', trigger: 'blur' }],
    insertStatus: [{ required: true, message: '新增状态不能为空', trigger: 'blur' }],
    updateStatus: [{ required: true, message: '修改状态不能为空', trigger: 'blur' }],
    queryCondition: [{ required: true, message: '查询条件不能为空', trigger: 'blur' }],
  });

  watch(visible, (v) => {
    if (v) {
      reset();
      if (props.detailId) {
        tableLoading.value = true;
        getTable(props.detailId)
          .then((res) => {
            form.value = {
              ...res.data,
              formCols: res.data.formCols.sort((a, b) => a.sortValue - b.sortValue),
            };
          })
          .finally(() => {
            tableLoading.value = false;
          });
        title.value = '修改';
      } else {
        handleAddPreset();
        title.value = '添加';
      }
    }
  });

  function reset() {
    form.value = {
      id: null,
      createBy: null,
      createTime: null,
      dataScopeType: 'noLimit',
      dataSourceId: '',
      deptId: null,
      deptIdFieldName: null,
      formCols: [],
      idStrategy: '自增',
      jd: null,
      jdFieldName: null,
      name: null,
      qu: null,
      quFieldName: null,
      seqName: null,
      sq: null,
      sqFieldName: null,
      tableCode: randomString(8),
      tableName: null,
      tableRemark: null,
      tags: '',
      updateBy: null,
      updateTime: null,
      userId: null,
      userIdFieldName: null,
      wg: null,
      wgFieldName: null,
      xq: null,
      xqFieldName: null,
    };
    tableRef.value?.resetFields();
    submitLoading.value = false;
    tableLoading.value = false;
    isAddCol.value = false;
    isEditCol.value = false;
    currItem.value = {};
    originalItem.value = {};
    activeFieldProperty.value = '基本属性';
    selectedCols.value = [];
  }

  function handleColSelectionChange(selection) {
    selectedCols.value = selection.map((k) => k);
  }

  function handleAddPreset() {
    const idItem = createColItem();
    Object.assign(idItem, {
      colName: 'ID',
      fieldName: '主键',
      fieldRemark: '主键',
      fieldType: 'DOUBLE',
      fieldLength: 20,
      primary: true,
      autoIncrement: false,
      allowNull: false,
      listStatus: '隐藏',
      insertStatus: '隐藏',
      updateStatus: '自动填充且隐藏',
    });
    form.value.formCols.push(idItem);
  }

  function createColItem() {
    const sort = form.value.formCols.length + 1;
    return {
      id: null,
      allowNull: true, // 允许空值
      autoFillExp: null, // 后端填充表达式
      autoFillExpWeb: null, // 前端填充表达式
      autoIncrement: null, // 是否自增
      colName: null, // 列名
      constantDictContent: null, // 常量字典内容
      controlType: null, // 控件类型
      desensitizationType: null, // 脱敏方式 (弃用)
      fieldDecimalLength: 0, // 小数
      fieldDefault: null, // 默认值
      fieldLength: 255, // 长度
      fieldName: null, // 字段名称
      fieldProperty: null, // 字段类别: 基本属性 数据库属性 页面属性 字典属性 校验配置 (弃用)
      fieldRemark: null, // 字段描述
      fieldType: null, // 类型
      format: null, // 格式字符串
      insertStatus: '正常', // 新增状态
      listStatus: '正常', // 列表状态
      needDesensitize: null,
      onlyInsert: null, // 仅新增时填充
      parentXzqhField: null, // 上级行政区划类型
      primary: null, // 是否主键
      queryCondition: 'not', // 查询条件
      regexpStr: null, // 正则校验
      relationDictType: null, // 字典类型
      required: null, // 是否必填
      sortValue: sort || 0, // 排序字段
      sysDictType: null, // 系统字典类型
      tableId: null, // 关联表id
      unique: null, // 是否唯一
      updateStatus: '正常', // 修改状态
      useOrderBy: null, // 使用此字段排序 降序desc 升序aesc
      validator: null, // 校验器
      xzqhlx: null, // 行政区划类型
    };
  }

  function handleAddColItem() {
    currItem.value = createColItem();
    isAddCol.value = true;
  }

  function handleEditColItem(item) {
    originalItem.value = item;
    currItem.value = { ...item };
    isEditCol.value = true;
    checkFieldTypeDisable(currItem.value);
  }

  function checkFieldTypeDisable(item) {
    if (isEditCol.value) {
      const { id, tableId } = item;
      if (id && tableId) {
        const params = {
          formTableId: tableId,
          formColId: id,
        };
        allowToModify(params).then((res) => {
          item.fieldTypeDisable = !res.data;
        });
      } else {
        item.fieldTypeDisable = false;
      }
    } else {
      item.fieldTypeDisable = false;
    }
  }

  function handleDelColItem(item) {
    const idx = form.value.formCols.indexOf(item);
    if (idx > -1) {
      form.value.formCols.splice(idx, 1);
    }
  }

  function handleBatchDelColItem() {
    for (let i = 0; i < selectedCols.value.length; i++) {
      const col = selectedCols.value[i];
      const idx = form.value.formCols.indexOf(col);
      if (idx > -1) {
        form.value.formCols.splice(idx, 1);
      }
    }
  }

  function handleConfirmItem() {
    colItemFormRef.value?.validate((valid, msg) => {
      if (valid) {
        if (isAddCol.value) {
          form.value.formCols.push({ ...currItem.value });
        } else if (isEditCol.value) {
          const idx = form.value.formCols.indexOf(originalItem.value);
          if (idx > -1) {
            form.value.formCols.splice(idx, 1, { ...currItem.value });
          }
        }
        form.value.formCols.sort((a, b) => a.sortValue - b.sortValue);
        handleCancelItem();
      } else {
        const key = Object.keys(msg)?.[0];
        if (key) {
          const message = msg[key]?.[0]?.message;
          if (message) {
            modal.msgError(message);
          }
        }
      }
    });
  }

  function handleCancelItem() {
    isAddCol.value = false;
    isEditCol.value = false;
  }

  function handleIsPrimaryChange(row) {
    const { primary } = row;
    if (primary) {
      row.allowNull = false;
    } else {
      row.autoIncrement = false;
    }
  }

  function handleRelationDictTypeChange(row) {
    const { relationDictType } = row;
    if (!relationDictType) {
      row.sysDictType = '';
      row.constantDictContent = '';
      row.xzqhlx = '';
      row.parentXzqhField = '';
    } else if (relationDictType === '系统字典') {
      row.constantDictContent = '';
    } else if (relationDictType === '常量字典') {
      row.sysDictType = '';
    } else if (relationDictType === '行政区划') {
      row.xzqhlx = '';
      row.parentXzqhField = '';
    }
  }

  function handleFieldTypeChange(row) {
    // const { fieldType } = row;
    row.fieldDecimalLength = 0;
    // row.queryCondition = null
    row.queryCondition = 'not';

    // if (fieldType !== 'NUMBER') {
    //   row.autoIncrement = false;
    //   row.fieldLength = 255;
    // } else {
    //   row.fieldLength = 20;
    // }
  }

  function handleFieldDefaultChange(v) {
    currItem.value['fieldDefault'] = (v || '').replace(/[^a-zA-Z0-9\u4e00-\u9fa5_]/g, '');
  }

  function handleFieldNameChange(v) {
    if (currItem.value.id) {
      return;
    }
    currItem.value.colName = `${pinyin(v, {
      style: pinyin.STYLE_NORMAL,
    })
      .map((k) => k?.[0]?.[0] ?? '')
      .filter((k) => !!k.match(/[a-zA-Z_]/))
      .join('')
      .slice(0, 26)}_${randomString(2)}`.toUpperCase();
  }

  function handleControlTypeChange(row) {
    row.format = null;
    // row.queryCondition = null
    row.queryCondition = 'not';
  }

  function handleNeedDesensitizeChange(row) {
    if (row.needDesensitize) {
      row.desensitizationType = 'defaultIdnoDesensitizer';
    } else {
      row.desensitizationType = null;
    }
  }

  function handleFormItemUpperCase(v, field) {
    form.value[field] = (v?.replace(/[^a-zA-Z_]/g, '') || '').toUpperCase();
  }

  // eslint-disable-next-line
  function handleColItemUpperCaseLetter(v, field) {
    currItem.value[field] = (v?.replace(/[^a-zA-Z0-9_]/g, '') || '').toUpperCase();
  }

  function autoIncrementDisabled(row) {
    const { fieldType, primary } = row;
    return !((fieldType === 'INTEGER' || fieldType === 'LONG') && primary);
  }

  function checkFieldDecimalLengthDisabled(row) {
    return !['INTEGER', 'LONG'].includes(row.fieldType);
  }

  function checkQueryConditionDisabled(row) {
    return ['upload', 'picture'].includes(row.controlType);
  }

  function checkQueryConditionItemDisabled(row, v) {
    const { fieldType } = row;
    if (v === 'like') {
      return fieldType !== 'STRING';
    }
    if (['gt', 'gte', 'lt', 'lte', 'range'].includes(v)) {
      return !['INTEGER', 'LONG', 'DOUBLE', 'LOCAL_DATE_TIME', 'LOCAL_DATE'].includes(fieldType);
    }
    return false;
  }

  function getAllField() {
    return (
      form.value.formCols
        .filter((k) => k.colName)
        .map((k) => ({
          value: k.colName,
          label: `${k.colName}${k.fieldName ? `（${k.fieldName}）` : ''}`,
        })) ?? []
    );
  }

  function handleCopyClick(v) {
    clipboardRef.value = v;
    if (unref(copiedRef)) {
      modal.msgSuccess('复制成功');
    }
  }

  function formatBool(row, { property }) {
    const val = row[property];
    return val ? '√' : '';
  }

  function formatFieldDecimalLength(row, { property }) {
    const v = row[property];
    return v || '-';
  }

  function formatBoolean(value) {
    if (value === null || value === undefined) {
      return '';
    }
    return value ? '是' : '否';
  }

  function submitForm() {
    const tableData = form.value.formCols;

    const keyList = tableData.map((k) => k.colName);
    const keySet = new Set(keyList);
    if (keyList.length !== keySet.size) {
      modal.msgError('存在重复列名');
      return;
    }
    if (isAddCol.value || isEditCol.value) {
      modal.msgError('请先保存表单列');
      return;
    }

    tableRef.value.validate((valid, msg) => {
      if (valid) {
        submitLoading.value = true;
        const params = {
          ...form.value,
          formCols: tableData,
        };
        if (form.value.id != null) {
          updateTable(params)
            .then(() => {
              modal.msgSuccess('修改成功');
              visible.value = false;
              emits('success');
            })
            .finally(() => {
              submitLoading.value = false;
            });
        } else {
          addTable(params)
            .then(() => {
              modal.msgSuccess('新增成功');
              visible.value = false;
              emits('success');
            })
            .finally(() => {
              submitLoading.value = false;
            });
        }
      } else {
        const key = Object.keys(msg)?.[0];
        if (key) {
          const message = msg[key]?.[0]?.message;
          if (message) {
            modal.msgError(message);
          }
        }
      }
    });
  }

  // eslint-disable-next-line
  function handleColItemChinese(v, field) {
    currItem.value[field] = v?.replace(/[^\u4e00-\u9fa5]/g, '') || '';
  }

  // eslint-disable-next-line
  function checkFormatDisabled(row) {
    return !['TimePicker', 'DatePicker', 'DatetimePicker'].includes(row.controlType);
  }
</script>
